//
//  AppDelegate.m
//  Keping
//
//  Created by 柯平 on 2017/6/16.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "AppDelegate.h"
#import "HomeViewController.h"
#import "KLocateCommand.h"
#import "KCommandManage.h"
#import "KDatabase.h"
#import "KLoginViewController.h"
#import "KClearNavigationController.h"
#import "KLaunchViewController.h"
#import "KTabBarController.h"
#import "KNavigationController.h"
#import <IQKeyboardManager.h>
#import <Hyphenate/Hyphenate.h>
#import <GoogleMaps/GoogleMaps.h>
#import "AppDelegate+IM.h"
#import <GooglePlacePicker/GooglePlacePicker.h>
#import <GooglePlaces/GooglePlaces.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import "WXApi.h"
#import "GPNewFeatureController.h"

// 引入JPush功能所需头文件
#import <JPush/JPUSHService.h>
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<JPUSHRegisterDelegate> {
    CLLocationManager *locationManager;/*定位服务*/
}
@property(nonatomic,strong)YYReachability* reachability;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //定位
    [self locateAction];
    
    
    [ShareSDK registerActivePlatforms:@[
                                        @(SSDKPlatformTypeSMS),
                                        @(SSDKPlatformTypeWechat),
                                        @(SSDKPlatformTypeWhatsApp)
                                        ]
                             onImport:^(SSDKPlatformType platformType) {
                                 switch (platformType) {
                                     case SSDKPlatformTypeWechat:
                                         [ShareSDKConnector connectWeChat:[WXApi class]];
                                         break;
                                     default:
                                         break;
                                 }
                             } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
                                 switch (platformType) {
                                     case SSDKPlatformTypeWechat:
                                         [appInfo SSDKSetupWeChatByAppId:@"wx3e755135d6b221e0"//wxfccf5565db6c82b4
                                       appSecret:@"9f1ced0844174fdeeb2febb069d843b9"];// 088787f972a6cc4a00e6acb4648c8ef6
                                         break;
                                     default:
                                         break;
                                 }
                             }];
    
    
    //进度条/提示框配置
    [[KAppConfig sharedConfig] setHudType:HudShowTypeMB];
    
    //google 地图 AIzaSyAgfRElQEfVN4-0NFDNmWNfJHNLhvVa30k
//    [GMSServices provideAPIKey:@"AIzaSyAET1hIIT7wI_kkYIVdCu-59M6O05eSMgQ"];
    [GMSServices provideAPIKey:@"AIzaSyAgfRElQEfVN4-0NFDNmWNfJHNLhvVa30k"];
    [GMSPlacesClient provideAPIKey:@"AIzaSyAs6BB-ff36csAb79KXMo3uP9lE98hHSlU"];
    
    //建表
    //[KDatabase createTablesNeeded];
    
    //keyboard
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
    [[IQKeyboardManager sharedManager] setToolbarDoneBarButtonItemText:@"Done"];
    
    //网络
    self.reachability = [YYReachability reachability];
    KLog(@"当前网络状态：%@",self.reachability.status == YYReachabilityStatusNone ? @"无网络":self.reachability.status == YYReachabilityStatusWiFi ? @"WiFi网络":@"移动网络");
    [KAppConfig sharedConfig].networkStatus = self.reachability.status;
    @weakify(self);
    self.reachability.notifyBlock = ^(YYReachability *reachability){
        [weak_self networkChanged:reachability];
    };
    
    //服务器配置
    [[KNetworkConfig sharedConfig] setBaseUrl:KBaseURL];
    [[KAppConfig sharedConfig] setRequestTimeInterval:30.0];
    
    //环信配置
    [self setupIM:launchOptions];
    
    //推送配置
    [self setupPushWithOptions:launchOptions];
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    /*
     if (![[KAppConfig sharedConfig] isNoneFirstOpen]) {
     self.window.rootViewController = [[KLoginViewController alloc]init];
     [[KAppConfig sharedConfig] setIsNoneFirstOpen:YES];
     }else{
     self.window.rootViewController = [[KTabBarController alloc]init];
     }
     */
    if ([self isNewFeture]) {
        WEAKSELF
        GPNewFeatureController *vc = [[GPNewFeatureController alloc] initWithNibName:[GPNewFeatureController className] bundle:nil];
        vc.callback = ^{
            if ([weakSelf isUserLogin]) {
                [weakSelf appAutoLogin];
            }else{
                weakSelf.window.rootViewController = [[KNavigationController alloc] initWithRootViewController:[[KLoginViewController alloc]init]];
            }
        };
        self.window.backgroundColor = [UIColor whiteColor];
        self.window.rootViewController = vc;
        [self.window makeKeyAndVisible];
        return YES;
    }
    if ([self isUserLogin]) {
        [self appAutoLogin];
    }else{
        self.window.rootViewController = [[KNavigationController alloc] initWithRootViewController:[[KLoginViewController alloc]init]];
    }
    [self.window makeKeyAndVisible];
    
    return YES;
}

-(void)locateAction
{
    KLocateCommand * locateCmd = [[KLocateCommand alloc]init];
    locateCmd.timeOutDefault = 60.0f;
    [KCommandManage executeCommand:locateCmd completeBlock:^(id<Command> cmd) {
        if (locateCmd.responseStatus == KLocateStatusSuccess) {
            KLog(@"City:%@",locateCmd.cityName);
        }
    }];
}

-(void)networkChanged:(YYReachability*)reachability{
    YYReachabilityStatus status = reachability.status;
    switch (status) {
        case YYReachabilityStatusNone:
        {
            KLog(@"网络服务已断开");
        }
            break;
        case YYReachabilityStatusWiFi:
        {
            [self isNetworkResume];
        }
            break;
        case YYReachabilityStatusWWAN:
        {
            KLog(@"移动网络");
            [self isNetworkResume];
            YYReachabilityWWANStatus wwStatus = reachability.wwanStatus;
            switch (wwStatus) {
                case YYReachabilityWWANStatus2G:
                    KLog(@"2G网络");
                    break;
                case YYReachabilityWWANStatus3G:
                    KLog(@"4G网络");
                    break;
                case YYReachabilityWWANStatus4G:
                    KLog(@"4G网络");
                    break;
                case YYReachabilityWWANStatusNone:
                    KLog(@"无移动网络");
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
    
    //更新网络状态
    [KAppConfig sharedConfig].networkStatus = status;
}

-(void)isNetworkResume
{
    if ([[KAppConfig sharedConfig] networkStatus] == YYReachabilityStatusNone) {
        KLog(@"网络已恢复：WIFI网络");
        //1.刷新首页数据
        
#warning NetworkResume
        [[NSNotificationCenter defaultCenter] postNotificationName:@"KNetworkResumeKey" object:nil];
        //2.重新定位
        [self locateAction];
    }
}

- (BOOL)isNewFeture
{
    NSString *curVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"]; // 获取当前的版本号
    NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"__versionNumber__"]; // 获取上一次的版本号
    if (!lastVersion) {
        [[NSUserDefaults standardUserDefaults] setObject:curVersion forKey:@"__versionNumber__"];
        return YES;
    }
    if ([curVersion isEqualToString:lastVersion]) { // 版本号相等, 不显示新特性
        return NO;
    }else{ // 是新特性
        [[NSUserDefaults standardUserDefaults] setObject:curVersion forKey:@"__versionNumber__"];
        return YES;
    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    //环信推送
    [self gp_applicationDidEnterBackground:application];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    CLAuthorizationStatus locationStatus = [CLLocationManager authorizationStatus];
    if (locationStatus != [KAppConfig sharedConfig].locationStatus) {
        [[KAppConfig sharedConfig] setLocationStatus:locationStatus];
        [[NSNotificationCenter defaultCenter] postNotificationName:KLocationAuthorizedStatusChangedNotification object:nil];
    }
    
    //环信推送
    [self gp_applicationWillEnterForeground:application];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation
{
    KLog(@"application:openURL:sourceApplication:annotation:");
    //    [self application:application handleOpenURL:url];
    return  YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    KLog(@"application:handleOpenURL:");
    //    [self application:application openURL:url sourceApplication:nil annotation:nil];
    return  YES;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    KLog(@"application:openURL:options:");
    //    [self application:app handleOpenURL:url];
    return  YES;
}

//  你需要通过重写这个方法，来重写你的通知内容，也可以在这里下载附件内容
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *contentToDeliver))contentHandler {
    
}

//  如果处理时间太长，等不及处理了，就会把收到的apns直接展示出来
- (void)serviceExtensionTimeWillExpire {
    
}


/*     推送   */


- (void)setupPushWithOptions:(NSDictionary *)launchOptions
{
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:@"99f6133fd09481dcb813a267"
                          channel:@"App store"
                 apsForProduction:NO
            advertisingIdentifier:nil];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    } else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionAlert |
                                                          UNAuthorizationOptionBadge |
                                                          UNAuthorizationOptionSound)
                                              categories:nil];
    }
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    //清除badge
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// 环信的离线推送
    [[EMClient sharedClient] bindDeviceToken:deviceToken];
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    //收到推送的请求
    UNNotificationRequest *request = notification.request;
    //收到推送的内容
    UNNotificationContent *content = request.content;
    //收到用户的基本信息
    NSDictionary *userInfo = content.userInfo;
    //收到推送消息的角标
    NSNumber *badge = content.badge;
    //收到推送消息body
    NSString *body = content.body;
    //推送消息的声音
    UNNotificationSound *sound = content.sound;
    // 推送消息的副标题
    NSString *subtitle = content.subtitle;
    // 推送消息的标题
    NSString *title = content.title;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //此处省略一万行需求代码。。。。。。
        KLog(@"iOS10 收到远程通知:%@",userInfo);
    }else {
        // 判断为本地通知
        //此处省略一万行需求代码。。。。。。
        KLog(@"iOS10 收到本地通知:{\\\\nbody:%@，\\\\ntitle:%@,\\\\nsubtitle:%@,\\\\nbadge：%@，\\\\nsound：%@，\\\\nuserInfo：%@\\\\n}",body,title,subtitle,badge,sound,userInfo);
    }
    // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    completionHandler(UNNotificationPresentationOptionBadge|
                      UNNotificationPresentationOptionSound|
                      UNNotificationPresentationOptionAlert);
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        KLog(@"iOS10 收到远程通知:%@", userInfo);
    }
    else {
        // 判断为本地通知
        KLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    KLog(@"iOS7及以上系统，收到通知:%@", userInfo);
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    KLog(@"iOS6及以下系统，收到通知:%@", userInfo);
    // Required,For systems with less than or equal to iOS6
    // 取得 APNs 标准信息内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    
    // 取得Extras字段内容
    NSString *customizeField1 = [userInfo valueForKey:@"extras"]; //服务端中Extras字段，key是自己定义的
    KLog(@"content =[%@], badge=[%d], sound=[%@], customize field  =[%@]",content,badge,sound,customizeField1);
    
    // iOS 10 以下 Required
    [JPUSHService handleRemoteNotification:userInfo];
}

@end
